package com.zrrd.mcl.activity.controller;

import com.alibaba.nacos.client.naming.utils.StringUtils;
import com.zrrd.mcl.activity.service.SeckillGoodsService;
import com.zrrd.mcl.activity.util.CacheHelper;
import com.zrrd.mcl.common.result.Result;
import com.zrrd.mcl.common.result.ResultCodeEnum;
import com.zrrd.mcl.common.util.AuthContextHolder;
import com.zrrd.mcl.common.util.DateUtil;
import com.zrrd.mcl.common.util.MD5;
import com.zrrd.mcl.model.activity.OrderRecode;
import com.zrrd.mcl.model.activity.SeckillGoods;
import com.zrrd.mcl.model.activity.UserRecode;
import com.zrrd.mcl.model.order.OrderDetail;
import com.zrrd.mcl.model.order.OrderInfo;
import com.zrrd.mcl.model.user.UserAddress;
import com.zrrd.mcl.order.client.OrderFeignClient;
import com.zrrd.mcl.rabbit.constant.MqConstant;
import com.zrrd.mcl.rabbit.service.RabbitService;
import com.zrrd.mcl.service.constant.RedisConst;
import com.zrrd.mcl.user.client.UserFeignClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.*;

@RestController
@RequestMapping("/api/activity/seckill")
public class SeckillGoodsApiController {

    @Autowired
    private SeckillGoodsService seckillGoodsService;

    @Autowired
    private RabbitService rabbitService;

    @Autowired
    private RedisTemplate redisTemplate;
    @Qualifier("com.zrrd.mcl.user.client.UserFeignClient")
    @Autowired
    private UserFeignClient userFeignClient;
    @Qualifier("com.zrrd.mcl.order.client.OrderFeignClient")
    @Autowired
    private OrderFeignClient orderFeignClient;

    //秒杀商品下单
    @PostMapping("/auth/seckillOrder/{skuId}")
    public Result seckillOrder(@PathVariable("skuId") Long skuId, HttpServletRequest request) {

        //校验下单码
        String userId = AuthContextHolder.getUserId(request);
        String skuIdstr = request.getParameter("skuIdStr");
        if (!skuIdstr.equals(MD5.encrypt(userId))) {
            System.out.println("下单码不正确====>");
            //请求不合法
            return Result.build(null, ResultCodeEnum.SECKILL_ILLEGAL);
        }
        //校验状态位
        String state = (String) CacheHelper.get(skuId.toString());
        System.out.println("状态位====>" + state);
        if (StringUtils.isEmpty(state)) {
            //请求不合法
            return Result.build(null, ResultCodeEnum.SECKILL_ILLEGAL);
        }
        if (!"1".equals(state)) {
            //没有库存
            return Result.build(null, ResultCodeEnum.SECKILL_FINISH);
        } else {
            //创建角色记录
            UserRecode recode = new UserRecode();
            recode.setUserId(userId);
            recode.setSkuId(skuId);
            //发送MQ消息
            rabbitService.sendMessage(MqConstant.EXCHANGE_DIRECT_SECKILL_USER, MqConstant.ROUTING_SECKILL_USER, recode);
            System.out.println("发送下单请求MQ消息====>" + recode);
        }
        return Result.ok();
    }


    //添加秒杀商品
    @GetMapping("/addSeckillGoods/{skuId}")
    public Result addSeckillGoods(@PathVariable("skuId") Long skuId) {
        seckillGoodsService.addSeckillGoods(skuId);
        return Result.ok("添加成功");
    }

    //查看秒杀商品列表
    @GetMapping("/findAll")
    public Result findAll() {
        return Result.ok(seckillGoodsService.getSeckillGoodsList());
    }

    //获取商品详情
    @GetMapping("/getSeckillGoods/{skuId}")
    public Result getSeckillGoods(@PathVariable("skuId") Long skuId) {
        return Result.ok(seckillGoodsService.getSeckillGoodsById(skuId));
    }

    //获取下单码
    @GetMapping("/auth/getSeckillSkuIdStr/{skuId}")
    public Result getSeckillSkuIdStr(@PathVariable("skuId") Long skuId, HttpServletRequest request) {
        //获取用户ID
        String userId = AuthContextHolder.getUserId(request);
        //根据sku获取商品信息
        SeckillGoods seckillGoods = seckillGoodsService.getSeckillGoodsById(skuId);
        if (seckillGoods != null) {
            //判断库存
            if (seckillGoods.getStockCount() <= 0) {
                return Result.fail().message(seckillGoods.getSkuName() + "库存不足");
            }
            //判断是否是当天的商品
            Date date = new Date();
            if (DateUtil.dateCompare(seckillGoods.getStartTime(), date) && DateUtil.dateCompare(date, seckillGoods.getEndTime())) {
                //生成下单码 ---> 使用MD5将userid加密
                String skuIdstr = MD5.encrypt(userId);
                System.out.println("获取下单码===>userId===>" + userId);
                System.out.println("下单码===>" + skuIdstr);
                return Result.ok(skuIdstr);
            }
        }
        return Result.fail().message("抢购商品已经不存在");
    }

    //查询下单
    @GetMapping("/auth/checkOrder/{skuId}")
    public Result checkOrder(@PathVariable("skuId") Long skuId, HttpServletRequest request) {
        String userId = AuthContextHolder.getUserId(request);
        return seckillGoodsService.checkorder(skuId, userId);
    }

    //秒杀商品订单结算数据
    @GetMapping("/auth/trade")
    public Result trade(HttpServletRequest request) {
        //获取用户ID
        String userId = AuthContextHolder.getUserId(request);
        //获取用户要购买的商品
        OrderRecode orderRecode = (OrderRecode) redisTemplate.boundHashOps(RedisConst.SECKILL_ORDERS).get(userId);
        if (orderRecode == null) {
            return Result.fail().message("非法操作");
        }
        //获取秒杀商品对象
        SeckillGoods seckillGoods = orderRecode.getSeckillGoods();
        //获取用户收货地址
        List<UserAddress> userAddresses = userFeignClient.findUserAddressByUserId(userId);
        //组装订单明细
        List<OrderDetail> detailList = new ArrayList<>();
        OrderDetail detail = new OrderDetail();
        detail.setSkuId(seckillGoods.getSkuId());
        detail.setSkuName(seckillGoods.getSkuName());
        detail.setSkuNum(1);
        detail.setImgUrl(seckillGoods.getSkuDefaultImg());
        detail.setOrderPrice(seckillGoods.getCostPrice());
        detailList.add(detail);

        //计算总金额
        OrderInfo orderInfo = new OrderInfo();
        orderInfo.setOrderDetailList(detailList);
        orderInfo.sumTotalAmount();

        //创建返回的Map集合
        Map<String, Object> map = new HashMap<>();
        map.put("userAddressList", userAddresses);
        map.put("detailArrayList", detailList);
        map.put("totalAmount", orderInfo.getTotalAmount());

        return Result.ok(map);
    }

    //秒杀提交订单
    @PostMapping("/auth/submitOrder")
    public Result submitOrder(@RequestBody OrderInfo orderInfo, HttpServletRequest request) {
        //设置用户ID
        String userId = AuthContextHolder.getUserId(request);
        orderInfo.setUserId(Long.parseLong(userId));
        //调用订单服务完成订单提交
        Long orderId = orderFeignClient.submitOrder(orderInfo);
        if (orderId == null) {
            return Result.fail().message("下单失败，请重新操作");
        }
        //删除订单信息
        redisTemplate.boundHashOps(RedisConst.SECKILL_ORDERS).delete(userId);
        //存入下单记录
        redisTemplate.boundHashOps(RedisConst.SECKILL_ORDERS_USERS).put(userId, orderId.toString());
        return Result.ok(orderId);
    }

}
